package com.service;
import java.io.IOException;
import java.net.Socket;

public class Dispatch implements Runnable{
    
    private Socket client;
    private Request request;
    private Response response;
    private int code = 200;
    public Dispatch(Socket client) {
        this.client = client;
        try {
            request = new Request(client.getInputStream());
            response = new Response(client.getOutputStream());
        } catch (IOException e) {
            //e.printStackTrace();
            code = 500;
            return ;
        }
    }
    public void run() {
        try{
            String action = request.getAction();
            Servlet servlet = WebApp.getServlet(action);
            if(servlet == null){
                this.code = 404;
                response.pushToClient(code);
                return;
            }
            servlet.service(request, response);
            /*String method = request.getMethod();
            if(method.equalsIgnoreCase("post")){
                servlet.doPost(request, response);
            }else if(method.equalsIgnoreCase("get")){
                servlet.doGet(request, response);
            }*/
        } catch (Exception e) {
            e.printStackTrace();
            code = 500;
        }
        //设置返回给用户的页面内容
        response.htmlContent("This is my page");
        //返回给用户的内容（响应头+html）
        response.pushToClient(code);
        try {
            client.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}